package com.fancon.android.gardenjokesx.activity;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import me.openphoto.android.app.provider.UploadsProviderAccessor;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fancon.android.emoji.widget.RichEditText;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.FlickrUser;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.Place;
import com.fancon.android.gardenjokesx.entity.TumblrUser;
import com.fancon.android.gardenjokesx.entity.TwitterUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.entity.WeiboUser;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.services.UploaderService;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

// Sua them lop Mediaconnect

public class P06Activity extends GardenJokesBaseActivity implements
		MediaScannerConnectionClient {
	public static Uri mImageCaptureUri;
	public static Uri mImageCropUri;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int DRAW_RAGE = 4;
	private static final int PICK_FROM_FILE = 3;
	private File captureFile;
	private String selectedImagePath;
	private ImageView attachThumb;
	private Bitmap attacheBitMap = null;
	private View attachementImage;
	//
	private LinearLayout rowAttachment;
	private LinearLayout p06_friend;

	private Button mBtnShare;

	// Link social network button
	private Button mBtnFacebook;
	private Button mBtnTwitter;
	private Button mBtnFlickr;
	private Button mBtnTumblr;
	private Button mBTnWeibo;

	// Geotag button
	private Button mBtnAttachment;

	// Text
	private TextView mTvTag1;
	private TextView mTvTag2;
	private TextView mTvFriends;
	private RichEditText mEditComment;
	private TextView mTvLocation;
	private TextView mTvLocationText;

	// Assessment button status.
	private boolean LIKE = Constant.ON;
	private boolean CUTE = Constant.OFF;
	private boolean COOL = Constant.OFF;
	private boolean YUMMY = Constant.OFF;

	// Social network button status.
	private boolean FACEBOOK, TWITTER, TUMBLR, FLICKR, WEIBO;
	private boolean isImageAttach = Constant.OFF;
	private boolean mTag1 = false, mTag2 = false;

	private DatabaseHelper mDb;
	private Bundle bundle;
	private User mUser;

	// List user with this user when post photo
	private ArrayList<FacebookUser> listFacebookUser;
	private String listFriends = "";
	private String listFBFriends = "";
	String listFriendID = "";
	// Place where shot photo
	private Place place = null;
	// List Tag with photo.
	private String tagsName = "";
	private String url_id = Constant.URL_PHOTO_ID_EMPTY;
	private String photo_url = "";
	private String tag1 = "";
	private String tag2 = "";
	private long longitude = 1000;
	private long latitude = 1000;

	// screen id to go get friend screen
	public static final int GET_FRIEND = 123;
	// screen id to go get geotag
	public static final int GET_GEOTAG = 321;
	// Rrequest code to get tag
	public static final int REQUEST_TAG = 124;
	public static final int REQUEST_FACEBOOK = 125;
	public static final int REQUEST_TWITTER = 126;
	public static final int REQUEST_TUMBLR = 127;
	public static final int REQUEST_FLICKR = 128;
	public static final int REQUEST_WEIBO = 129;

	protected LocationManager lm;
	protected MyLocationListener locationListener;
	private Location location;
	private boolean postOK = false;
	// Bitmap variable to hold bitmap image post tio server
	private static Bitmap bm;
	private MediaScannerConnection conn;
	private String savedFile;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.p06_layout);
		// bindKeyBoard();
		if (getIntent().getExtras() != null) {
			bundle = getIntent().getExtras();
			bundle.putInt(Constant.PRE_SCREEN_ID,
					bundle.getInt(Constant.SCREEN_ID));
			bundle.putInt(Constant.SCREEN_ID, Constant.P06);
			setBtnState(bundle);
		} else {
			// binhbt-added
			bundle = new Bundle();
		}
		mUser = UserUtil.getInfoUserLogin(P06Activity.this);

		mDb = new DatabaseHelper(P06Activity.this);
		rowAttachment = (LinearLayout) findViewById(R.id.p06_linearLayout_geotag);
		p06_friend = (LinearLayout) findViewById(R.id.p06_linearLayout_friend);
		// Share button.
		mBtnShare = (Button) findViewById(R.id.p06_shareButton);
		mBtnShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Post photo to meshtile server
				// RequestPostPhoto request = new RequestPostPhoto("p06",
				// P06Activity.this);
				// getGlobalState().getRequestQueue().addRequest(request);
				if(!isImageAttach&&(mEditComment.getText().length() == 0)){
					new AlertDialog.Builder(P06Activity.this)
					.setMessage(R.string.upload_notice)
					.setPositiveButton(R.string.ok,null)
					//.setNegativeButton(R.string.common_calcel, null)
					.show();
				}else{
					if (isImageAttach) {
						startUpload();
					} else {
						RequestPostPhoto request = new RequestPostPhoto("p06",
								P06Activity.this);
						getGlobalState().getRequestQueue().addRequest(request);
					}
				}
			}
		});
		attachThumb = (ImageView) findViewById(R.id.attach_thumb);
		attachementImage = findViewById(R.id.attachement_image);
		// Social network button.
		mBtnFacebook = (Button) findViewById(R.id.p06_btnFacebook);
		mBtnFlickr = (Button) findViewById(R.id.p06_btnFlickr);
		mBtnTumblr = (Button) findViewById(R.id.p06_btnTumblr);
		mBtnTwitter = (Button) findViewById(R.id.p06_btnTwitter);
		mBTnWeibo = (Button) findViewById(R.id.p06_btnWeibo);
		// --->set default state
		setButtonDefaultState(mBtnFacebook, mUser.getUser_id());
		setButtonDefaultState(mBtnFlickr, mUser.getUser_id());
		setButtonDefaultState(mBtnTumblr, mUser.getUser_id());
		setButtonDefaultState(mBtnTwitter, mUser.getUser_id());
		setButtonDefaultState(mBTnWeibo, mUser.getUser_id());
		// -->Set on click.
		setOnClick(mBtnFacebook);
		setOnClick(mBtnFlickr);
		setOnClick(mBtnTumblr);
		setOnClick(mBtnTwitter);
		setOnClick(mBTnWeibo);

		mTvFriends = (TextView) findViewById(R.id.p06_tvFriends);
		mTvLocation = (TextView) findViewById(R.id.p06_tvLocation);
		mTvLocationText = (TextView) findViewById(R.id.p06_tvLocation1);
		mEditComment = (RichEditText) findViewById(R.id.p06_editComment);

		// Geotag button.
		mBtnAttachment = (Button) findViewById(R.id.p06_btnGeotag);
		setGeotagBtn();
		// @binhbt
		selectedImagePath = bundle.getString(Constant.IMAGE_PATH);
		if (selectedImagePath != null) {
			loadComic();
		}
		mBtnAttachment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// doAttach();
				if (isImageAttach == Constant.OFF) {
					if (attacheBitMap == null) {
						doAttach();
					} else {
						isImageAttach = Constant.ON;
						attachementImage.setVisibility(View.VISIBLE);
						setGeotagBtn();
					}
				} else {
					isImageAttach = Constant.OFF;
					attachementImage.setVisibility(View.GONE);
					setGeotagBtn();
				}
			}
		});

		rowAttachment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				doAttach();
			}
		});

		p06_friend.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mDb.isFacebookLinked(mUser.getUser_id())) {
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						return true;
					}
					if (event.getAction() == MotionEvent.ACTION_UP) {
						p06_friend
								.setBackgroundResource(R.drawable.p06_tag_down_bg);
						Intent intent = new Intent(getApplicationContext(),
								P063Activity.class);
						saveState();
						if (listFacebookUser == null) {
							listFacebookUser = new ArrayList<FacebookUser>();
						}
						bundle.putSerializable(Constant.LIST_FRIEND,
								listFacebookUser);
						intent.putExtras(bundle);
						startActivityForResult(intent, GET_FRIEND);
						return true;
					}
				} else {
					// Show alert connect to facebook dialog.
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								P06Activity.this);
						builder.setMessage(
								getBaseContext().getResources().getString(
										R.string.MSG_P0017))
								.setCancelable(true)
								.setNegativeButton(
										getResources().getString(
												R.string.common_ok),
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.cancel();
											}
										});
						AlertDialog alert = builder.create();
						alert.show();
					}
				}
				return true;
			}
		});
		// Get intent, action and MIME type
		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			String sendText = null;
			String urlImg = null;
			if ("text/plain".equals(type)) {
				sendText = getSendText(intent); // Handle text being sent
				if (sendText != null) {
					mEditComment.setText(sendText);
				}
			} else if (type.startsWith("image/")) {
				urlImg = getSendImage(intent); // Handle single image being sent
				selectedImagePath = urlImg;
				loadComic();
			}
			if (mUser == null || mUser.getUser_id() == null
					|| mUser.getUser_id().length() == 0) {
				Intent in = new Intent(this, LoginActivity.class);
				if (sendText != null) {
					intent.putExtra("send_txt", sendText);
				}
				if (urlImg != null) {
					intent.putExtra(Constant.IMAGE_PATH, urlImg);
				}
				finish();
				startActivity(in);

			}
		}
	}

	private String getSendText(Intent intent) {
		String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
		if (sharedText != null) {
			// Update UI to reflect text being shared
			return sharedText;
		}
		return null;
	}

	private String getSendImage(Intent intent) {
		Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
		if (imageUri != null) {
			// Update UI to reflect image being shared
			return getRealPathFromURI(imageUri);
		}
		return null;
	}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private void loadComic() {
		try {
			FileInputStream fileis = new FileInputStream(selectedImagePath);
			BufferedInputStream bufferedstream = new BufferedInputStream(fileis);
			byte[] bMapArray = new byte[bufferedstream.available()];
			bufferedstream.read(bMapArray);
			attacheBitMap = BitmapFactory.decodeByteArray(bMapArray, 0,
					bMapArray.length);
			// Here you can set this /Bitmap image to the button background
			// image
			attachThumb.setImageBitmap(attacheBitMap);
			isImageAttach = Constant.ON;
			attachementImage.setVisibility(View.VISIBLE);
			setGeotagBtn();

			if (fileis != null) {
				fileis.close();
			}
			if (bufferedstream != null) {
				bufferedstream.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bundle b = new Bundle();
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == DRAW_RAGE) {
			selectedImagePath = data.getStringExtra(Constant.IMAGE_PATH);
			try {
				FileInputStream fileis = new FileInputStream(selectedImagePath);
				BufferedInputStream bufferedstream = new BufferedInputStream(
						fileis);
				byte[] bMapArray = new byte[bufferedstream.available()];
				bufferedstream.read(bMapArray);
				attacheBitMap = BitmapFactory.decodeByteArray(bMapArray, 0,
						bMapArray.length);
				// Here you can set this /Bitmap image to the button background
				// image
				attachThumb.setImageBitmap(attacheBitMap);
				isImageAttach = Constant.ON;
				attachementImage.setVisibility(View.VISIBLE);
				setGeotagBtn();

				if (fileis != null) {
					fileis.close();
				}
				if (bufferedstream != null) {
					bufferedstream.close();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		if (resultCode == RESULT_OK && requestCode == PICK_FROM_CAMERA) {
			attacheBitMap = (Bitmap) data.getExtras().get("data");
			OutputStream outStream = null;
			try {
				outStream = new FileOutputStream(captureFile);
				attacheBitMap.compress(Bitmap.CompressFormat.PNG, 100,
						outStream);
				attachThumb.setImageBitmap(attacheBitMap);
				isImageAttach = Constant.ON;
				attachementImage.setVisibility(View.VISIBLE);
				setGeotagBtn();
				outStream.flush();
				outStream.close();
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			return;
		}
		if (resultCode == RESULT_OK && requestCode == PICK_FROM_FILE) {
			Uri selectedImageUri = data.getData();
			selectedImagePath = getPath(selectedImageUri);
			try {
				FileInputStream fileis = new FileInputStream(selectedImagePath);
				BufferedInputStream bufferedstream = new BufferedInputStream(
						fileis);
				byte[] bMapArray = new byte[bufferedstream.available()];
				bufferedstream.read(bMapArray);
				attacheBitMap = BitmapFactory.decodeByteArray(bMapArray, 0,
						bMapArray.length);
				// Here you can set this /Bitmap image to the button background
				// image
				attachThumb.setImageBitmap(attacheBitMap);
				isImageAttach = Constant.ON;
				attachementImage.setVisibility(View.VISIBLE);
				setGeotagBtn();

				if (fileis != null) {
					fileis.close();
				}
				if (bufferedstream != null) {
					bufferedstream.close();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		if (resultCode == RESULT_OK && requestCode == GET_FRIEND) {
			listFriends = "";
			listFBFriends = "";
			listFacebookUser = (ArrayList<FacebookUser>) data.getExtras()
					.getSerializable(Constant.LIST_FRIEND);

			for (int i = 0; i < listFacebookUser.size(); i++) {
				if (listFriends.equals("")) {
					listFriends = listFacebookUser.get(i).getUsername();
					listFBFriends = "@["
							+ listFacebookUser.get(i).getFacebookId() + ":"
							+ listFacebookUser.get(i).getUsername() + "]";
				} else {
					listFriends = listFriends + ","
							+ listFacebookUser.get(i).getUsername();
					listFBFriends = listFBFriends + "," + "@["
							+ listFacebookUser.get(i).getFacebookId() + ":"
							+ listFacebookUser.get(i).getUsername() + "]";
				}

				if (listFriendID.equals("")) {
					listFriendID = listFacebookUser.get(i).getFacebookId();
				} else {
					listFriendID = listFriendID + ","
							+ listFacebookUser.get(i).getFacebookId();
				}
			}
			if (listFriends.length() > 0) {// if have friend
				mTvFriends.setText(StringUtil.validString(listFriends, 25));
				mTvFriends.setTextColor(getResources().getColor(R.color.black));
			}

		} else if (resultCode == RESULT_CANCELED && requestCode == GET_FRIEND) {// No
																				// friend
																				// selected
			listFacebookUser = new ArrayList<FacebookUser>();
			mTvFriends.setText(getResources().getString(
					R.string.p06_friend_text));
			mTvFriends.setTextColor(getResources().getColor(R.color.grey));
		}

		// TODO get geotag
		if (resultCode == RESULT_OK && requestCode == GET_GEOTAG) {
			place = (Place) data.getExtras().getSerializable("location");
			setGeotagBtn();
		}

		// TODO get Tag from P061
		if (resultCode == RESULT_OK && requestCode == REQUEST_TAG) {
			b = data.getExtras();
			setText(b);
		}

		if (resultCode == RESULT_OK && requestCode == REQUEST_TWITTER) {
			b = data.getExtras();
			TWITTER = b.getBoolean(Constant.LINK_STATE);
			Log.d("P06", "result twitter: " + TWITTER);
		}

		if (resultCode == RESULT_OK && requestCode == REQUEST_FACEBOOK) {
			b = data.getExtras();
			FACEBOOK = b.getBoolean(Constant.LINK_STATE);
			Log.d("P06", "result facebook: " + FACEBOOK);
		}

		if (resultCode == RESULT_OK && requestCode == REQUEST_FLICKR) {
			b = data.getExtras();
			FLICKR = b.getBoolean(Constant.LINK_STATE);
			Log.d("P06", "result flickr: " + FLICKR);
		}

		if (resultCode == RESULT_OK && requestCode == REQUEST_TUMBLR) {
			b = data.getExtras();
			TUMBLR = b.getBoolean(Constant.LINK_STATE);
			Log.d("P06", "result tumblr: " + TUMBLR);
		}

		if (resultCode == RESULT_OK && requestCode == REQUEST_WEIBO) {
			b = data.getExtras();
			WEIBO = b.getBoolean(Constant.LINK_STATE);
			Log.d("P06", "result weibo: " + WEIBO);
		}
		setSocialBtnState();
	}

	/**
	 * Set button state with current state
	 */
	private void setBtnState(Bundle b) {
		if (b != null) {
			// Assessment state
			if (b.get("like") != null) {
				LIKE = b.getBoolean("like");
			}

			if (b.get("cute") != null) {
				CUTE = b.getBoolean("cute");
			}

			if (b.get("cool") != null) {
				COOL = b.getBoolean("cool");
			}

			if (b.get("Yummy") != null) {
				YUMMY = b.getBoolean("yummy");
			}

			// GEOTAG button state.
			if (b.get("geotag") != null) {
				isImageAttach = b.getBoolean("geotag");
			}

			// Social network button state.
			if (b.get("facebook") != null) {
				FACEBOOK = b.getBoolean("facebook");
			}

			if (b.get("twitter") != null) {
				TWITTER = b.getBoolean("twitter");
			}

			if (b.get("flickr") != null) {
				FLICKR = b.getBoolean("flickr");
			}

			if (b.get("tumblr") != null) {
				TUMBLR = b.getBoolean("tumblr");
			}

			if (b.get("weibo") != null) {
				WEIBO = b.getBoolean("weibo");
			}

		}

	}

	private void setText(Bundle b) {
		if (b != null) {
			int i = b.getInt(Constant.TAG_SET);
			if (b.get(Constant.TAG_NAME).toString().length() > 0) {

				String tag = StringUtil.validString(b.get(Constant.TAG_NAME)
						.toString(), 25);

				if (i == 1 && !tag.equals(tag2)) {
					mTvTag1.setText("#" + tag);
					tag1 = tag;
					mTvTag1.setTextColor(getResources().getColor(R.color.black));
					mTag1 = true;
				} else if (i == 2 && !tag.equals(tag1)) {
					mTvTag2.setText("#" + tag);
					tag2 = tag;
					mTvTag2.setTextColor(getResources().getColor(R.color.black));
					mTag2 = true;
				}

			} else {
				if (i == 1) {
					mTvTag1.setText(getResources().getString(
							R.string.p06_tag_text));
					mTvTag1.setTextColor(getResources().getColor(R.color.grey));
					tag1 = "";
					mTag1 = false;
				} else {
					mTvTag2.setText(getResources().getString(
							R.string.p06_tag_text));
					mTvTag2.setTextColor(getResources().getColor(R.color.grey));
					mTag2 = false;
					tag2 = "";
				}
			}

		}
	}

	/********************************* SAVE P06 STATE ********************************************/
	/**
	 * Save P06's fields value to send to other screen
	 */
	private void saveState() {
		if (bundle == null) {
			bundle = new Bundle();
		}
		bundle.putInt(Constant.SCREEN_ID, Constant.P06);
		return;
	}

	/********************************* GEOTAG BUTTON *******************************************/
	private void setGeotagBtn() {

		if (!isImageAttach) {
			mBtnAttachment.setBackgroundResource(R.drawable.p06_btn_geotag_off);
			mBtnAttachment.setText(getResources().getString(
					R.string.p06_geo_tag_text_off));
			// mTvLocation.setText(getResources().getString(
			// R.string.p06_geotag_off));
			mTvLocation.setTextColor(getResources().getColor(R.color.grey));
			mTvLocationText.setVisibility(View.GONE);

		} else {
			mBtnAttachment.setBackgroundResource(R.drawable.p06_btn_geotag_on);
			mBtnAttachment.setText(getResources().getString(
					R.string.p06_geotag_on));
			mTvLocation.setTextColor(getResources().getColor(R.color.black));
			mTvLocationText
					.setTextColor(getResources().getColor(R.color.black));

			if (place == null || place.getName().length() == 0) {
				// mTvLocation.setText(getResources().getString(
				// R.string.p06_geotag_off));
				mTvLocationText.setVisibility(View.VISIBLE);
			} else {
				Log.d("P06", "Geotag: on have place");
				// mTvLocation.setText(place.getName());
				mTvLocationText.setVisibility(View.GONE);
			}
		}
	}

	/********************************* ASSESSMENT BUTTON ***********************************************************/
	/**
	 * Set Assessment button with default status: btnLike is ON, other button is
	 * OFF.
	 */
	// private void setAssessmentBtnState() {
	// int white = getResources().getColor(R.color.white);
	//
	// if (LIKE == Constant.ON) {
	// mBtnLike.setBackgroundResource(R.drawable.p06_button_good_active);
	// mBtnLike.setTextColor(white);
	// } else {
	// mBtnLike.setBackgroundResource(R.drawable.p06_button_good);
	// }
	//
	// if (CUTE == Constant.ON) {
	// mBtnCute.setBackgroundResource(R.drawable.p06_button_love_active);
	// } else {
	// mBtnCute.setBackgroundResource(R.drawable.p06_button_love);
	// }
	//
	// if (COOL == Constant.ON) {
	// mBtnCool.setBackgroundResource(R.drawable.p06_button_star_active);
	// } else {
	// mBtnCool.setBackgroundResource(R.drawable.p06_button_star);
	// }
	//
	// if (YUMMY == Constant.ON) {
	// mBtnYummy.setBackgroundResource(R.drawable.p06_button_food_active);
	// } else {
	// mBtnYummy.setBackgroundResource(R.drawable.p06_button_food);
	// }
	// return;
	// }

	/***************************************** SOCIAL NEWORK CONNECT BUTTON ***************************************/
	/**
	 * Check button state
	 * 
	 * @param btn
	 *            : Button
	 * @return state of button: ON(true), OFF( false)
	 */
	private boolean getBtnState(Button v) {
		boolean state = Constant.ON;

		switch (v.getId()) {
		case R.id.p06_btnFacebook:
			state = FACEBOOK;
			break;
		case R.id.p06_btnFlickr:
			state = FLICKR;
			break;
		case R.id.p06_btnTwitter:
			state = TWITTER;
			break;
		case R.id.p06_btnTumblr:
			state = TUMBLR;
			break;
		case R.id.p06_btnWeibo:
			state = WEIBO;
			break;
		default:
			state = Constant.OFF;
			break;
		}
		return state;
	}

	/**
	 * 
	 * @param btn
	 * @param userId
	 */
	private void setBtnState(Button v, String userId) {
		bundle.putInt(Constant.SCREEN_ID, Constant.P06);
		boolean currentState = getBtnState(v);

		if (currentState == Constant.ON) {// if button is active
			switch (v.getId()) {
			case R.id.p06_btnFacebook:
				v.setBackgroundResource(R.drawable.common_icon_facebook_deactive);
				FACEBOOK = Constant.OFF;
				break;
			case R.id.p06_btnFlickr:
				v.setBackgroundResource(R.drawable.common_icon_flickr_deactive);
				FLICKR = Constant.OFF;
				break;
			case R.id.p06_btnTwitter:
				v.setBackgroundResource(R.drawable.common_icon_twitter_deactive);
				TWITTER = Constant.OFF;
				break;
			case R.id.p06_btnTumblr:
				v.setBackgroundResource(R.drawable.common_icon_tumblr_deactive);
				TUMBLR = Constant.OFF;
				break;
			case R.id.p06_btnWeibo:
				v.setBackgroundResource(R.drawable.common_icon_weibo_deactive);
				WEIBO = Constant.OFF;
				break;
			default:
				break;
			}
		} else if (currentState == Constant.OFF) {
			Bundle b = new Bundle();
			b.putInt(Constant.SCREEN_ID, Constant.P06);
			b.putBoolean(Constant.LINK_STATE, Constant.OFF);
			switch (v.getId()) {
			case R.id.p06_btnFacebook:
				if (mDb.isFacebookLinked(userId)) {
					v.setBackgroundResource(R.drawable.common_icon_facebook_active);
					FACEBOOK = Constant.ON;
				} else {
					Intent i = new Intent(getBaseContext(), S03_2Activity.class);
					i.putExtras(b);
					startActivityForResult(i, REQUEST_FACEBOOK);
				}
				break;
			case R.id.p06_btnFlickr:
				if (mDb.isFlickrLinked(userId)) {
					v.setBackgroundResource(R.drawable.common_icon_flickr_active);
					FLICKR = Constant.ON;
				} else {
					Intent i = new Intent(getBaseContext(), S03_3Activity.class);
					i.putExtras(b);
					startActivityForResult(i, REQUEST_FLICKR);
				}
				break;
			case R.id.p06_btnTwitter:
				if (mDb.isTwitterLinked(userId)) {
					v.setBackgroundResource(R.drawable.common_icon_twitter_active);
					TWITTER = Constant.ON;
				} else {
					Intent i = new Intent(getBaseContext(), S03_1Activity.class);
					i.putExtras(b);
					startActivityForResult(i, REQUEST_TWITTER);
				}
				break;
			case R.id.p06_btnTumblr:
				if (mDb.isTumblrLinked(userId)) {
					v.setBackgroundResource(R.drawable.common_icon_tumblr_active);
					TUMBLR = Constant.ON;
				} else {
					Intent i = new Intent(getBaseContext(), S03_4Activity.class);
					i.putExtras(b);
					startActivityForResult(i, REQUEST_TUMBLR);
				}
				break;
			case R.id.p06_btnWeibo:
				if (mDb.isWeiboLinked(userId)) {
					v.setBackgroundResource(R.drawable.common_icon_weibo_active);
					WEIBO = Constant.ON;
				} else {
					Intent i = new Intent(getBaseContext(), S03_7Activity.class);
					i.putExtras(b);
					startActivityForResult(i, REQUEST_WEIBO);
				}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * Set button with appropriate background and text base on current state.
	 * 
	 * @param btn
	 *            : Button.
	 * @param state
	 *            : Boolean( ON-true, OFF-false). State to set to button.
	 */
	private void setButtonDefaultState(Button btn, String userId) {
		switch (btn.getId()) {
		case R.id.p06_btnFacebook:
			if (mDb.isFacebookLinked(userId)) {
				FACEBOOK = Constant.ON;
				btn.setBackgroundResource(R.drawable.common_icon_facebook_active);
			} else {
				FACEBOOK = Constant.OFF;
				btn.setBackgroundResource(R.drawable.common_icon_facebook_deactive);
			}
			break;
		case R.id.p06_btnTumblr:
			if (mDb.isTumblrLinked(userId)) {
				TUMBLR = Constant.ON;
				btn.setBackgroundResource(R.drawable.common_icon_tumblr_active);
			} else {
				TUMBLR = Constant.OFF;
				btn.setBackgroundResource(R.drawable.common_icon_tumblr_deactive);
			}
			break;
		case R.id.p06_btnTwitter:
			if (mDb.isTwitterLinked(userId)) {
				TWITTER = Constant.ON;
				btn.setBackgroundResource(R.drawable.common_icon_twitter_active);
			} else {
				TWITTER = Constant.OFF;
				btn.setBackgroundResource(R.drawable.common_icon_twitter_deactive);
			}
			break;
		case R.id.p06_btnFlickr:
			if (mDb.isFlickrLinked(userId)) {
				FLICKR = Constant.ON;
				btn.setBackgroundResource(R.drawable.common_icon_flickr_active);
			} else {
				FLICKR = Constant.OFF;
				btn.setBackgroundResource(R.drawable.common_icon_flickr_deactive);
			}
			break;
		case R.id.p06_btnWeibo:
			if (mDb.isWeiboLinked(userId)) {
				WEIBO = Constant.ON;
				btn.setBackgroundResource(R.drawable.common_icon_weibo_active);
			} else {
				WEIBO = Constant.OFF;
				btn.setBackgroundResource(R.drawable.common_icon_weibo_deactive);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * Set social button state with current state.
	 */
	private void setSocialBtnState() {
		if (FACEBOOK) {
			mBtnFacebook
					.setBackgroundResource(R.drawable.common_icon_facebook_active);
		} else {
			mBtnFacebook
					.setBackgroundResource(R.drawable.common_icon_facebook_deactive);
		}

		if (TWITTER) {
			mBtnTwitter
					.setBackgroundResource(R.drawable.common_icon_twitter_active);
		} else {
			mBtnTwitter
					.setBackgroundResource(R.drawable.common_icon_twitter_deactive);
		}

		if (FLICKR) {
			mBtnFlickr
					.setBackgroundResource(R.drawable.common_icon_flickr_active);
		} else {
			mBtnFlickr
					.setBackgroundResource(R.drawable.common_icon_flickr_deactive);
		}

		if (TUMBLR) {
			mBtnTumblr
					.setBackgroundResource(R.drawable.common_icon_tumblr_active);
		} else {
			mBtnTumblr
					.setBackgroundResource(R.drawable.common_icon_tumblr_deactive);
		}

		if (WEIBO) {
			mBTnWeibo
					.setBackgroundResource(R.drawable.common_icon_weibo_active);
		} else {
			mBTnWeibo
					.setBackgroundResource(R.drawable.common_icon_weibo_deactive);
		}
		return;
	}

	/**
	 * Social button on click listener.
	 * 
	 * @param btn
	 */
	private void setOnClick(Button btn) {
		// Log.v("click", "click state: "+getBtnState((Button)v));
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setBtnState((Button) v, mUser.getUser_id());
			}
		});
	}

	private int getTagNum() {
		if (mTag1 == true && mTag2 == true) {
			return 2;
		} else if (mTag1 == false && mTag2 == false) {
			return 0;
		} else {
			return 1;
		}
	}

	// private String getTag() {
	// String tag = "";
	// if (mTag1 == true) {
	// tag = mTvTag1.getText().toString().substring(1);
	// }
	// if (mTag2 == true && mTag1 == true) {
	// tag = tag + "," + mTvTag2.getText().toString().substring(1);
	// } else if (mTag2 == true) {
	// tag = mTvTag2.getText().toString().substring(1);
	// }
	//
	// return tag;
	// }

	private int getButtonType() {
		int btnType = Constant.BUTTON_TYPE_LIKE;
		if (LIKE == Constant.ON) {
			btnType = Constant.BUTTON_TYPE_LIKE;
		} else if (COOL == Constant.ON) {
			btnType = Constant.BUTTON_TYPE_COOL;
		} else if (CUTE == Constant.ON) {
			btnType = Constant.BUTTON_TYPE_CUTE;
		} else if (YUMMY == Constant.ON) {
			btnType = Constant.BUTTON_TYPE_YUMMY;
		}
		return btnType;
	}

	/******************************* DO POST **********************************/
	// Post image to meshtiles server
	// TODO Post to server
	private String postToServer() {
		Log.d("P06", "post photo");
		if (place == null || !isImageAttach) {
			place = new Place();
			place.setLatitude(1000);
			place.setLongitude(1000);
			place.setName("");
			place.setIdPlace("-1");
			Log.d("P06", "set location");
		}
		if (location != null) {
			longitude = (long) location.getLongitude();
			latitude = (long) location.getLatitude();
		}

		// create list tag parameter.
		// Log.d("P06", "tag1: " + mTag1 + " , tag2: " + mTag2);
		// tagsName = getTag();
		tagsName = "";
		Charset chars = Charset.forName("UTF-8");
		MultipartEntity reqEntity = new MultipartEntity();

		try {
			// Log.d("P06", "image url: " + bundle.getString("imagepath"));
			int quality = 50;
			try {
				long realSize = getImageLength(selectedImagePath);
				quality = (int) (5 * Constant.X_SIZE / realSize);
				quality = quality > 90 ? 90 : quality;
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			if (isImageAttach == Constant.ON) {
				if (attacheBitMap != null) {
					attacheBitMap.compress(CompressFormat.JPEG, quality, bos);
				}
			}
			// Log.d("<<<< bitmap size pure",
			// "..."+getImageLength(selectedImagePath));
			Log.d("<<<< bitmap size", "quality " + quality + "..." + bos.size());
			byte[] data = bos.toByteArray();
			ByteArrayBody bad = new ByteArrayBody(data, "");

			reqEntity.addPart("user_id", new StringBody(mUser.getUser_id()));
			reqEntity.addPart("photo_object", bad);
			reqEntity.addPart("button_type", new StringBody(""
					+ getButtonType()));

			reqEntity.addPart("longitude", new StringBody("" + longitude));

			reqEntity.addPart("latitude", new StringBody("" + latitude));

			reqEntity.addPart(
					"comment",
					new StringBody(""
							+ URLEncoder.encode(mEditComment.getRichText(),
									"UTF-8").replace("+", "%20"), chars));
			String comment = mEditComment.getRichText();
			Log.d("P06", "comment: " + comment);
			reqEntity.addPart("filter_id",
					new StringBody(String.valueOf(bundle.getInt("filterID"))));

			reqEntity.addPart("location_latitude",
					new StringBody("" + place.getLatitude()));

			// Log.d("P06", "longitude: " + place.getLongitude());
			reqEntity.addPart("location_longitude",
					new StringBody("" + place.getLongitude()));

			// Log.d("P06", "latitude: " + place.getLatitude());
			reqEntity.addPart(
					"location_text",
					new StringBody(""
							+ URLEncoder.encode(place.getName(), "UTF-8")
									.replace("+", "%20")));

			reqEntity.addPart("location_id",
					new StringBody("" + place.getIdPlace()));

			Log.d("P06", "location id: " + place.getIdPlace());
			reqEntity.addPart("model", new StringBody(Build.MODEL));
			Log.d("P06", "model: " + Build.MODEL);
			reqEntity.addPart(
					"timezone",
					new StringBody(String.valueOf(TimeZone.getDefault()
							.getRawOffset() / (60 * 60 * 1000))));

			reqEntity.addPart("friend", new StringBody("{\"friend\":"
					+ parseToJsonArray(listFacebookUser).toString() + "}",
					chars));
			Log.d("P06",
					"friends: " + "{\"friend\":"
							+ parseToJsonArray(listFacebookUser).toString()
							+ "}");

			reqEntity.addPart("list_tags", new StringBody("" + tagsName));
			Log.d("P06", "list tag: " + tagsName);

			reqEntity.addPart(
					"client_time",
					new StringBody(String.valueOf(java.text.DateFormat
							.getDateTimeInstance().format(
									Calendar.getInstance().getTime()))));
			bos.close();

		} catch (Exception e) {
			return null;
		}
		GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
				P06Activity.this);
		return apiConnect.execPostImg(P06Activity.this,
				GardenJokesApiConnect.GROUP_P, "postPhoto", reqEntity);
	}

	public long getImageLength(String absFileName) {
		File file = new File(absFileName);
		return file.length();
	}

	/**
	 * Share image to social network.
	 */
	private void postToSocialNetwork() {
		Log.d("P06", "Post social network!");
		String imagePath = selectedImagePath;
		if (imagePath == null || !isImageAttach) {
			imagePath = Constant.XCOMIC_ICON_ASSET;
		}
		Log.d("P06", "Image Path: " + imagePath);
		SocialUntil social = new SocialUntil(this);
		boolean result = false;

		if (FACEBOOK == Constant.ON) {
			FacebookUser fbUser = mDb.getFacebookUser(mUser.getUser_id());
			Log.d("P06", "facebook");
			String accessToken = fbUser.getAccessToken();
			Log.d("P06", "facebook access: " + accessToken + ", message: "
					+ getFacebookMessage());
			// checkins
			if (place != null && place.getName().toString().length() > 0) {
				result = social.checkInToFacebook(photo_url,
						getFacebookMessage(), accessToken, place, listFriendID,
						url_id);
				Log.v("P06", "Check in to facebook: " + result);
				// post
			} else {
				result = social.postToFacebook(imagePath, getFacebookMessage(),
						accessToken);
				Log.v("P06", "Post to facebook: " + result);
			}

		}

		// Post to tumblr
		if (TUMBLR == Constant.ON) {
			TumblrUser tumUser = mDb.getTumblrUser(mUser.getUser_id());
			String email = tumUser.getUsername();
			String password = tumUser.getPassword();
			Log.d("P06", "tumblr email: " + email + ", message: "
					+ getTumblrMessage());
			result = social.postToTumblr(imagePath, getTumblrMessage(), email,
					password);
			Log.v("P06", "Post to Tumblr: " + result);
		}

		if (TWITTER == Constant.ON) {
			TwitterUser twiUser = mDb.getTwitterUser(mUser.getUser_id());
			String token = twiUser.getTwitterToken();
			String secret = twiUser.getTwitterSecret();
			Log.v("P06", "twitter token: " + token);
			Log.d("P06", " twitter message: " + getTwitterMessage());
			result = social.postToTwitter(imagePath, getTwitterMessage(),
					token, secret);
			Log.v("P06", "post to Twitter: " + result);
		}

		// Post to flickr.
		if (FLICKR == Constant.ON) {
			FlickrUser flUser = mDb.getFlickrUser(mUser.getUser_id());
			String token = flUser.getAccessToken();
			result = social.postToFlickr(imagePath, getFlickrMessage(), url_id,
					token);
			Log.v("P06", "post to Flickr: " + result);
		}
		// Post to weibo.
		if (WEIBO == Constant.ON) {
			// Log.d("P06", "weibo link: " +
			// mDb.isWeiboLinked(mUser.getUser_id()));
			WeiboUser weiUser = mDb.getWeiboUser(mUser.getUser_id());
			String token = weiUser.getWeiboToken();
			String secret = weiUser.getWeiboSecret();
			result = social.postToWeibo(imagePath, getWeiboMessage(), "", "",
					token, secret);
			Log.v("P06", "post to Weibo: " + result);
		}
	}

	private JSONArray parseToJsonArray(List<FacebookUser> fbUser) {
		JSONArray jArray = new JSONArray();
		if (fbUser != null) {
			for (int i = 0; i < fbUser.size(); i++) {
				jArray.put(fbUser.get(i).parseToJsonObject());
			}
		}
		Log.d("P06", "Json Friend: " + jArray.toString());
		return jArray;
	}

	/**
	 * Build message post to Weibo
	 * 
	 * @return
	 */
	private String getWeiboMessage() {
		String msg = "";
		String comment = mEditComment.getRichText();
		int tagNum = getTagNum();

		String placeName = "";
		if (place != null && place.getName().toString().length() > 0) {
			placeName = " @ " + place.getName();
		}

		switch (tagNum) {
		case 2:
			if (comment.length() > 0) {
				msg = getResources().getString(R.string.P06_WEIBO_2TAG_COMMENT,
						comment, tag1, tag2, placeName, url_id);
			} else {
				msg = getResources().getString(R.string.P06_WEIBO_2TAG, tag1,
						tag2, placeName, url_id);
			}
			break;

		case 1:
			String tag = (mTag1) ? tag1 : tag2;
			if (comment.length() > 0) {
				msg = getResources().getString(R.string.P06_WEIBO_1TAG_COMMENT,
						comment, tag, placeName, url_id);
			} else {
				msg = getResources().getString(R.string.P06_WEIBO_1TAG, tag,
						placeName, url_id);
			}
			break;

		default:
			if (comment.length() > 0) {
				msg = getResources().getString(R.string.P06_WEIBO_0TAG_COMMENT,
						comment, placeName, url_id);
			} else {
				msg = getResources().getString(R.string.P06_WEIBO_0TAG,
						placeName, url_id);
			}
			break;
		}
		return msg;
	}

	/**
	 * Buil message post to Facebook
	 * 
	 * @return
	 */
	private String getFacebookMessage() {
		String msg = ""; // Message is posted to facebook.
		String comment = mEditComment.getRichText().toString(); // Comment
//		int tagNum = getTagNum(); // Selected tag numbers.
		int tagNum = 0;
		String friend = "";
		Log.d("P06", "post url: " + url_id);

		// If have friends
		if (listFriends.length() > 0) {
			friend = " with " + listFBFriends;// listFriends;
		}

		// check in to facebook
		if (place != null && place.getName().toString().length() > 0) {
			switch (tagNum) {
			case 2:
				if (comment.length() > 0) {
					msg = getResources().getString(
							R.string.P06_FACEBOOK_2TAG_COMMENT, comment,
							"#" + tag1, " & #" + tag2, "", "", "");
				} else {
					msg = getResources().getString(R.string.P06_FACEBOOK_2TAG,
							"#" + tag1, " & #" + tag2, "", "", "");
				}
				break;

			case 1:
				String tag = (mTag1) ? tag1 : tag2;

				if (comment.length() > 0) {
					msg = getResources().getString(
							R.string.P06_FACEBOOK_1TAG_COMMENT, comment,
							"#" + tag, "", "", "");
				} else {
					msg = getResources().getString(R.string.P06_FACEBOOK_1TAG,
							"#" + tag, "", "", "");
				}
				break;

			default:
				if (comment.length() > 0) {
					msg = getResources().getString(
							R.string.P06_FACEBOOK_0TAG_COMMENT, comment, "",
							"", "");
				} else {
					msg = getResources().getString(R.string.P06_FACEBOOK_0TAG,
							"", "", "");
				}
				break;
			}

			// post image to album
		} else {
			switch (tagNum) {
			case 2:
				if (comment.length() > 0) {
					msg = getResources()
							.getString(R.string.P06_FACEBOOK_2TAG_COMMENT,
									comment, "#" + tag1, " & #" + tag2, "",
									friend, " " + url_id);
				} else {
					msg = getResources()
							.getString(R.string.P06_FACEBOOK_2TAG, "#" + tag1,
									" & #" + tag2, "", friend, " " + url_id);
				}
				break;

			case 1:
				String tag = (mTag1) ? tag1 : tag2;

				if (comment.length() > 0) {
					msg = getResources().getString(
							R.string.P06_FACEBOOK_1TAG_COMMENT, comment,
							"#" + tag, "", friend, " " + url_id);
				} else {
					msg = getResources().getString(R.string.P06_FACEBOOK_1TAG,
							"#" + tag, "", friend, " " + url_id);
				}
				break;

			default:
				if (comment.length() > 0) {
					msg = getResources().getString(
							R.string.P06_FACEBOOK_0TAG_COMMENT, comment, "",
							friend, " " + url_id);
				} else {
					msg = getResources().getString(R.string.P06_FACEBOOK_0TAG,
							"", friend, " " + url_id);
				}
				break;
			}
		}
		return msg;
	}

	/**
	 * Build message post to Tumblr
	 * 
	 * @return
	 */
	private String getTumblrMessage() {

		String msg = ""; // Message is posted to Tumblr
		String comment = mEditComment.getRichText().toString(); // Entered
																// comment
		int tagNum = getTagNum(); // Tag number
		String friend = "";
		String placeName = "";

		// If have friends
		if (listFriends.length() > 0) {
			friend = " with " + listFriends;
		}

		if (place != null && place.getName().toString().length() > 0) {
			placeName = " @ " + place.getName();
		}

		switch (tagNum) {
		case 2:
			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_TUMBLR_2TAG_COMMENT, comment, tag1, tag2,
						placeName, friend, url_id);
			} else {
				msg = getResources().getString(R.string.P06_TUMBLR_2TAG, tag1,
						tag2, placeName, friend, url_id);
			}
			break;

		case 1:
			String tag = (mTag1) ? tag1 : tag2;

			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_TUMBLR_1TAG_COMMENT, comment, tag,
						placeName, friend, url_id);
			} else {
				msg = getResources().getString(R.string.P06_TUMBLR_1TAG, tag,
						placeName, friend, url_id);
			}
			break;

		default:
			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_TUMBLR_0TAG_COMMENT, comment, placeName,
						friend, url_id);
			} else {
				msg = getResources().getString(R.string.P06_TUMBLR_0TAG,
						placeName, friend, url_id);
			}
			break;
		}

		return msg;
	}

	/**
	 * Build message post to Twitter
	 * 
	 * @return
	 */
	private String getTwitterMessage() {
		String msg = "";
		String comment = mEditComment.getRichText().toString();
		int tagNum = getTagNum();

		String placeName = "";

		if (place != null && place.getName().toString().length() > 0) {
			placeName = " @ " + place.getName();
		}

		switch (tagNum) {
		case 2:
			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_TWITTER_2TAG_COMMENT, comment, tag1, tag2,
						placeName, url_id);
			} else {
				msg = getResources().getString(R.string.P06_TWITTER_2TAG, tag1,
						tag2, placeName, url_id);
			}
			break;

		case 1:

			String tag = (mTag1) ? tag1 : tag2;

			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_TWITTER_1TAG_COMMENT, comment, tag,
						placeName, url_id);
			} else {
				msg = getResources().getString(R.string.P06_TWITTER_1TAG, tag,
						placeName, url_id);
			}
			break;

		default:
			if (comment.length() > 0) {
				if (placeName.length() > 0) {
					placeName = " (" + placeName + ")";
				}
				msg = getResources().getString(
						R.string.P06_TWITTER_0TAG_COMMENT, comment, placeName,
						url_id);
			} else {
				msg = getResources().getString(R.string.P06_TWITTER_0TAG,
						placeName, url_id);
			}
			break;
		}

		return msg;
	}

	/**
	 * Build message post to Flickr
	 * 
	 * @return
	 */
	private String getFlickrMessage() {
		String msg = "";
		String comment = mEditComment.getRichText().toString();
		int tagNum = getTagNum();
		String friend = "";
		String placeName = "";

		// If have friends
		if (listFriends.length() > 0) {
			friend = " with " + listFriends;
		}

		if (place != null && place.getName().toString().length() > 0) {
			placeName = " @ " + place.getName();
		}

		switch (tagNum) {
		case 2:
			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_FLICKR_2TAG_COMMENT, comment, tag1, tag2,
						placeName, friend);
			} else {
				msg = getResources().getString(R.string.P06_FLICKR_2TAG, tag1,
						tag2, placeName, friend);
			}
			break;

		case 1:

			String tag = (mTag1) ? tag1 : tag2;

			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_FLICKR_1TAG_COMMENT, comment, tag,
						placeName, friend);
			} else {
				msg = getResources().getString(R.string.P06_FLICKR_1TAG, tag,
						placeName, friend);
			}
			break;

		default:
			if (comment.length() > 0) {
				msg = getResources().getString(
						R.string.P06_FLICKR_0TAG_COMMENT, comment, placeName,
						friend);
			} else {
				msg = getResources().getString(R.string.P06_FLICKR_0TAG,
						placeName, friend);
			}
			break;
		}

		return msg;
	}

	class RequestPostPhoto extends RequestUI {
		private Activity context;
		private FanconProgressBar dialog;
		private Photo photo;

		public RequestPostPhoto(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			try {
				dialog = FanconProgressBar.show(context,
						context.getString(R.string.loading));
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void execute() throws Exception {
			long start = System.currentTimeMillis();
			String result = postToServer();
			// String result = postToServerNew();
			Log.d("Vao",
					"Vao P06 Post anh time: "
							+ (System.currentTimeMillis() - start));
			JsonPaser jP = new JsonPaser();
			photo = jP.postPhoto(result);
		}

		@Override
		public void executeUI(Exception ex) {
			// create our list and custom adapter
			try {
				dialog.setCancelable(true);
				dialog.dismiss();
				if (photo != null && photo.getUrl_id() != null) {
					url_id = photo.getUrl_id();
					photo_url = photo.getUrl_photo();
					Thread myThread = new Thread(new Runnable() {

						@Override
						public void run() {
							postToSocialNetwork();
						}
					});
					myThread.start();
					postOK = true;
				} else {
					postOK = false;
				}
				bundle.putSerializable(Constant.PHOTO, photo);
				// TODO Post to social network.
				// @binhbt-comment
				if (postOK) {
					Intent intent = new Intent(P06Activity.this,
							ProfileActivity.class);
					bundle.putString(Constant.USER_ID_VIEW, mUser.getUser_id());
					intent.putExtras(bundle);
					startActivity(intent);
					finish();
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	public String makeFilename(String prefix) {
		String direct = "/xcomic";

		File directory = new File(Environment.getExternalStorageDirectory()
				+ direct);
		if (!directory.exists()) {
			directory.mkdir();
		}
		File file = new File(directory, prefix
				+ String.valueOf(System.currentTimeMillis()) + ".png");
		Log.e("FILE", "FILE COPY : " + file.getPath());

		return Uri.fromFile(file).getPath();
	}

	public void copyFile(String input, String output) {
		try {
			Bitmap b = BitmapFactory.decodeFile(input);
			File file = new File(output);
			FileOutputStream fileOutputStream;

			fileOutputStream = new FileOutputStream(file);
			b.compress(CompressFormat.JPEG, 95, fileOutputStream);
			fileOutputStream.flush();
			fileOutputStream.close();
			b.recycle();
		} catch (FileNotFoundException e) {
			Log.e("P06Activity",
					"FileNotFoundException in copyFile(): " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("P06Activity", "IOException in copyFile(): " + e.getMessage());
			e.printStackTrace();
		}

	}

	public void getLocation() {
		/*
		 * launch a new Thread to get new location
		 */
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				if (lm == null) {
					lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				}

				if (locationListener == null) {
					locationListener = new MyLocationListener();
				}

				Criteria criteria = new Criteria();
				criteria.setAccuracy(Criteria.ACCURACY_COARSE);
				String provider = lm.getBestProvider(criteria, true);
				if (provider != null && lm.isProviderEnabled(provider)) {
					lm.requestLocationUpdates(provider, 1, 0, locationListener,
							Looper.getMainLooper());
				} else {
					/*
					 * GPS not enabled, prompt user to enable GPS in the
					 * Location menu
					 */

				}
				Looper.loop();
			}
		}.start();
	}

	class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {

			if (loc != null) {
				location = loc;
				lm.removeUpdates(this);
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	public void doAttach() {
		// TODO Auto-generated method stub
		final String[] items = new String[] {
				getApplicationContext().getString(R.string.draw_something),
				getApplicationContext().getString(R.string.p05_take_camera),
				getApplicationContext().getString(R.string.p05_select_library) };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, items);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle(getApplicationContext().getString(
				R.string.p05_select_title));
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {

				if (item == 0) {
					Intent intent = new Intent(P06Activity.this,
							ComicMakerActivity.class);
					intent.putExtra("p06", true);
					startActivityForResult(intent, DRAW_RAGE);
				} else if (item == 1) {
					captureFile = makeFilenamex("tmp_avatar_");
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					try {
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (ActivityNotFoundException e) {
						e.printStackTrace();
					}
				} else { // pick from file
					captureFile = makeFilenamex("tmp_avatar_");
					Intent intent = new Intent();

					intent.setType("image/*");
					intent.setAction(Intent.ACTION_PICK);
					startActivityForResult(intent, PICK_FROM_FILE);
				}
			}
		});

		final AlertDialog dialog = builder.create();

		dialog.show();
	}

	public File makeFilenamex(String prefix) {

		String direct = "/xcomic";

		File directory = new File(Environment.getExternalStorageDirectory()
				+ direct);
		if (!directory.exists()) {
			directory.mkdir();
		}
		File file = new File(directory, prefix
				+ String.valueOf(System.currentTimeMillis()));
		return file;
	}

	public static void p06SetNull() {
		Log.d("giai phong", "p06");
		if (bm != null) {
			bm.recycle();
			bm = null;
		}
	}

	// private void startScan() {
	// if (conn != null)
	// conn.disconnect();
	// conn = new MediaScannerConnection(P06Activity.this, P06Activity.this);
	// conn.connect();
	// }

	@Override
	public void onMediaScannerConnected() {
		// TODO Auto-generated method stub
		conn.scanFile(savedFile, null);
	}

	@Override
	public void onScanCompleted(String arg0, Uri arg1) {
		// TODO Auto-generated method stub
		conn.disconnect();
	}

	private void startUpload() {
		Log.d("P06", "post photo");
		if (place == null || !isImageAttach) {
			place = new Place();
			place.setLatitude(1000);
			place.setLongitude(1000);
			place.setName("");
			place.setIdPlace("-1");
			Log.d("P06", "set location");
		}
		if (location != null) {
			longitude = (long) location.getLongitude();
			latitude = (long) location.getLatitude();
		}

		// create list tag parameter.
		// Log.d("P06", "tag1: " + mTag1 + " , tag2: " + mTag2);
		// tagsName = getTag();
		tagsName = "";
		// Charset chars = Charset.forName("UTF-8");
		//

		UploadsProviderAccessor uploads = new UploadsProviderAccessor(this);
		// UploadMetaData metaData = new UploadMetaData();

		// metaData.setTitle(((EditText)
		// findViewById(R.id.edit_title)).getText().toString());
		// metaData.setDescription(((EditText)
		// findViewById(R.id.edit_description)).getText()
		// .toString());
		// metaData.setTags(((EditText)
		// findViewById(R.id.edit_tags)).getText().toString());
		// metaData.setPrivate(mPrivateToggle.isChecked());
		JSONObject data = new JSONObject();
		try {
			data.put("user_id", mUser.getUser_id());
			data.put("button_type", "" + getButtonType());
			data.put("longitude", "" + longitude);
			data.put("latitude", "" + latitude);
			data.put(
					"comment",
					""
							+ URLEncoder.encode(mEditComment.getRichText(),
									"UTF-8").replace("+", "%20"));
			data.put("filter_id", String.valueOf(bundle.getInt("filterID")));
			data.put("location_longitude", "" + place.getLongitude());
			data.put("location_latitude", "" + place.getLatitude());
			data.put(
					"location_text",
					""
							+ URLEncoder.encode(place.getName(), "UTF-8")
									.replace("+", "%20"));
			data.put("model", "" + Build.MODEL);
			data.put(
					"timezone",
					String.valueOf(TimeZone.getDefault().getRawOffset()
							/ (60 * 60 * 1000)));
			data.put("friend",
					"{\"friend\":"
							+ parseToJsonArray(listFacebookUser).toString()
							+ "}");
			data.put("list_tags", "" + tagsName);
			data.put("client_time", String.valueOf(java.text.DateFormat
					.getDateTimeInstance().format(
							Calendar.getInstance().getTime())));
			data.put("isImageAttach", isImageAttach);
			
			//For share to social network
			String imagePath = selectedImagePath;
			if (imagePath == null || !isImageAttach) {
				imagePath = Constant.XCOMIC_ICON_ASSET;
			}
			//
			data.put("isFacebook", FACEBOOK);
			data.put("isTumblr", TUMBLR);
			data.put("isTwitter", TWITTER);
			data.put("isFlickr", FLICKR);
			data.put("isWeibo", WEIBO);
			
			data.put("imagePath", imagePath);
			
			//Facebook
			if (FACEBOOK == Constant.ON) {
//				FacebookUser fbUser = mDb.getFacebookUser(mUser.getUser_id());
//				Log.d("P06", "facebook");
//				String accessToken = fbUser.getAccessToken();
				String fbMessage = getFacebookMessage();
				data.put("photo_url", photo_url);
				data.put("facebookMessage", fbMessage);
//				data.put("accessToken", accessToken);
				data.put("listFriendID", listFriendID);
				if (place != null && place.getName().toString().length() > 0) {
					data.put("place_name", place.getName().toString());
				}
			}
			//TUMBLR
			if (TUMBLR == Constant.ON) {
//				TumblrUser tumUser = mDb.getTumblrUser(mUser.getUser_id());
//				String email = tumUser.getUsername();
//				String password = tumUser.getPassword();
//				Log.d("P06", "tumblr email: " + email + ", message: "
//						+ getTumblrMessage());
//				result = social.postToTumblr(imagePath, getTumblrMessage(), email,
//						password);
				data.put("tumblrMessage", getTumblrMessage());
//				data.put("email", email);
//				data.put("password", password);
			}
			//TWITTER
			if (TWITTER == Constant.ON) {
//				TwitterUser twiUser = mDb.getTwitterUser(mUser.getUser_id());
//				String token = twiUser.getTwitterToken();
//				String secret = twiUser.getTwitterSecret();
//				Log.v("P06", "twitter token: " + token);
//				Log.d("P06", " twitter message: " + getTwitterMessage());
//				result = social.postToTwitter(imagePath, getTwitterMessage(),
//						token, secret);
				data.put("twitterMessage", getTwitterMessage());
//				data.put("token", token);
//				data.put("secret", secret);
			}
			// FLICKR
			if (FLICKR == Constant.ON) {
//				FlickrUser flUser = mDb.getFlickrUser(mUser.getUser_id());
//				String token = flUser.getAccessToken();
//				result = social.postToFlickr(imagePath, getFlickrMessage(), url_id,
//						token);
				data.put("flickrMessage", getTwitterMessage());
//				data.put("url_id", url_id);
//				data.put("token", token);
			}
			// WEIBO
			if (WEIBO == Constant.ON) {
				// Log.d("P06", "weibo link: " +
				// mDb.isWeiboLinked(mUser.getUser_id()));
//				WeiboUser weiUser = mDb.getWeiboUser(mUser.getUser_id());
//				String token = weiUser.getWeiboToken();
//				String secret = weiUser.getWeiboSecret();
//				result = social.postToWeibo(imagePath, getWeiboMessage(), "", "",
//						token, secret);
				data.put("weiboMessage", getWeiboMessage());
//				data.put("token", token);
//				data.put("secret", secret);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		File uploadFile = new File(selectedImagePath);
		uploads.addPendingUploadx(Uri.fromFile(uploadFile), data, false);
		// uploads.addPendingUpload(Uri.fromFile(uploadFile), metaData);
		startService(new Intent(this, UploaderService.class));
		Toast.makeText(this, R.string.uploading_in_background,
				Toast.LENGTH_LONG).show();
		Intent i = new Intent(this, GardenJokesActivity.class);
		startActivity(i);
		finish();
	}
}
